# -*- coding: utf-8 -*-

import requests
from urllib.parse import urljoin
from common_sdk.logging.logger import logger
from service import errors
from service import error_codes


class BaseClient:

    # domain = "http://business-service:5000"
    domain = "http://127.0.0.1:5000"

    def do_post(self, uri, params=None, headers=None, timeout=None, retry_times=None):
        result = self.__do_post(uri, params=params, timeout=timeout, headers=headers).json()
        msg = f"""
        调用business_service的接口: {uri}
        {params}
        {result}
        """
        logger.info(msg)
        return result

    def do_protobuf_post(self, uri, params=None, headers=None, timeout=None, retry_times=None):
        result = self.__do_post(uri, params, headers, timeout, retry_times)
        return result

    def do_http_post(self, uri, params=None, headers=None, timeout=None, retry_times=None):
        result = self.__do_post(uri, params, headers, timeout).json()
        return result

    def do_http_post_only_data(self, uri, params=None, headers=None, timeout=None, retry_times=None):
        result = self.__do_post(uri, params, headers, timeout).json()
        data = result.get("data")
        if result.get("errcode") != error_codes.SUCCESS[0]:
            raise errors.CustomMessageError(result.get("errmsg"))
        return data

    def __do_post(self, uri, params=None, headers=None, timeout=None, retry_times=None):
        if self.domain is None:
            return
        if timeout is None:
            timeout = 30
        if retry_times is None:
            retry_times = 0
        url = urljoin(self.domain, uri)
        try:
            result = requests.post(url, json=params, timeout=timeout, headers=headers)
            return result
        except requests.exceptions.ReadTimeout as ex:
            if retry_times > 0:
                return self.do_post(
                    uri, params,
                    headers=headers, timeout=int(timeout / 3), retry_times=retry_times-1)
            logger.exception(ex)
            raise ex
        except requests.exceptions.ConnectionError as ex:
            logger.exception(ex)
            raise ex
        except Exception as ex:
            logger.exception(ex)
            raise ex
